package com.redrose.rxandroiddemo.main.viewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.redrose.rxandroiddemo.bean.Chapter;
import com.redrose.rxandroiddemo.bean.Response;
import com.redrose.rxandroiddemo.service.Api;
import com.redrose.rxandroiddemo.util.HttpUtil;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainViewModel extends ViewModel {
    public MutableLiveData<List<Chapter>> chapterLiveData = new MutableLiveData<>();
    private Api api = HttpUtil.getOnlineCookieRetrofit().create(Api.class);

    public MutableLiveData<List<Chapter>> getChapterLiveData() {
        return chapterLiveData;
    }

    public void getChapters() {
        api.getChapters().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Response<Chapter>>() {
                    @Override
                    public void accept(Response<Chapter> chapterResponse) throws Throwable {
                        List<Chapter> chapterList= chapterResponse.getData();
                        chapterLiveData.setValue(chapterList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {//处理异常
                        throwable.printStackTrace();
                    }
                });
    }

    private void getChapterListById(int id, int pageSize) {
        api.getChapterListById(id, pageSize).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Response<String>>() {
                    @Override
                    public void accept(Response<String> chapterChildItemResponse) throws Throwable {
                        List<String> data = chapterChildItemResponse.getData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {//处理异常
                        throwable.printStackTrace();
                    }
                });
    }

    public void onItemClick(Chapter chapter) {
        getChapterListById(chapter.getId(),1);
    }
}
